package com.picket.controller;

import java.util.EnumSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.appengine.api.users.UserServiceFactory;
import com.picket.domain.AppRole;
import com.picket.domain.GaeUser;
import com.picket.form.RegistrationForm;
import com.picket.security.GaeUserAuth;
import com.picket.service.IGaeUserService;

@Controller
public class RegisterController {

     private IGaeUserService gaeUserService;
     private final String[] admins = {"srillion@gmail.com","mukul37@gmail.com","test@example.com"};

    @RequestMapping(value="/register", method= RequestMethod.GET)
    public String doShowRegister(Model model)
	{
		final RegistrationForm registrationForm= new RegistrationForm();
		model.addAttribute("registrationForm", registrationForm);
		return "/register";
	} 
  /*  public RegistrationForm registrationForm() {
        return new RegistrationForm();
    }
    */

	@RequestMapping(value="/register", method = RequestMethod.POST)
	public String register(RegistrationForm form, BindingResult result) {
		if (result.hasErrors()) {
			return null;
		}
		
		if(form.getFirstname() == null || form.getFirstname().trim().length()==0  
				|| form.getLastname()==null || form.getLastname().trim().length() ==0){
			return "redirect:/register";
		}
		
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        GaeUser currentUser = (GaeUser)authentication.getPrincipal();
        Set<AppRole> roles = EnumSet.of(AppRole.USER);

        if (UserServiceFactory.getUserService().isUserAdmin()) {
            roles.add(AppRole.ADMIN);
        }
        for(String admin: admins){
        	if(admin.equalsIgnoreCase(currentUser.getEmail())){
        		roles.add(AppRole.ADMIN);
        	}
        }


        GaeUser user = new GaeUser(currentUser.getUserId(), currentUser.getNickname(), currentUser.getEmail(),
                form.getFirstname(), form.getLastname(), roles, true);

        gaeUserService.registerUser(user);

        // Update the context with the full authentication
        SecurityContextHolder.getContext().setAuthentication(new GaeUserAuth(user, authentication.getDetails()));

		return "redirect:/landing";
	}
	
	@Required
	public void setGaeUserService(IGaeUserService gaeUserService){
		this.gaeUserService = gaeUserService;
	}
}
